package com.asset.dispoal.evidenceconfig.service;

import com.asset.dispoal.evidenceconfig.api.BsEvidenceConfItemDetailService;
import com.asset.dispoal.evidenceconfig.api.BsEvidenceConfItemService;
import com.asset.dispoal.evidenceconfig.domain.db.entity.BsEvidenceConfItem;
import com.asset.dispoal.evidenceconfig.domain.db.mapper.BsEvidenceConfItemDetailMapper;
import com.asset.dispoal.evidenceconfig.domain.db.mapper.BsEvidenceConfItemMapper;
import com.asset.dispoal.evidenceconfig.domain.db.mapper.BsEvidenceConfMapper;
import com.asset.dispoal.evidenceconfig.domain.dto.EvidenceConfQueryIdsDto;
import com.asset.dispoal.evidenceconfig.domain.dto.EvidenceConfRespIdsDto;
import com.asset.dispoal.evidenceconfig.dto.request.BsEvidenceConfItemDetailRequest;
import com.asset.dispoal.evidenceconfig.dto.request.BsEvidenceConfItemRequest;
import com.asset.dispoal.evidenceconfig.dto.response.BsEvidenceConfItemResponse;
import com.asset.dispoal.evidenceconfig.service.converter.BsEvidenceConfItemConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.core.protocol.page.PageUtil;
import tech.mhuang.pacebox.springboot.core.spring.util.DataUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;
import tech.mhuang.pacebox.springboot.protocol.data.Page;
import tech.mhuang.pacebox.springboot.protocol.data.PageVO;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qr
 * @date 2021/10/21$
 */
@Service
public class BsEvidenceConfItemServiceImpl implements BsEvidenceConfItemService {

    @Autowired
    private BsEvidenceConfItemMapper bsEvidenceConfItemMapper;

    @Autowired
    BaseIdeable<String> snowFlake;

    @Autowired
    BsEvidenceConfMapper bsEvidenceConfMapper;

    @Autowired
    BsEvidenceConfItemDetailMapper detailMapper;
    @Autowired
    BsEvidenceConfItemDetailService detailService;


    @Override
    public PageVO<BsEvidenceConfItemResponse> queryByConfId(BsEvidenceConfItemRequest bsEvidenceConfItemRequest) {
        PageVO<BsEvidenceConfItemResponse> pageVo = new PageVO<>();
        pageVo.setTotalSize(bsEvidenceConfItemMapper.queryByConfIdCount(bsEvidenceConfItemRequest));
        if (PageUtil.checkPage(pageVo.getTotalSize(), bsEvidenceConfItemRequest)) {
            Page<BsEvidenceConfItemRequest> page = new Page<>();
            page.setRecord(bsEvidenceConfItemRequest);
            page.setStart((bsEvidenceConfItemRequest.getStart() - 1) * bsEvidenceConfItemRequest.getRows());
            page.setRows(bsEvidenceConfItemRequest.getRows());
            List<BsEvidenceConfItem> bsEvidenceConfItems = bsEvidenceConfItemMapper.queryByConfId(page);
            List<BsEvidenceConfItemResponse> bsEvidenceConfItemResponses = BsEvidenceConfItemConverter.INSTANCE.dosToRes(bsEvidenceConfItems);
            pageVo.setResult(bsEvidenceConfItemResponses);
        }
        return pageVo;
    }

    @Override
    public void insertOrUpdate(BsEvidenceConfItemRequest bsEvidenceConfItemRequest, boolean th) {
        if (bsEvidenceConfItemRequest == null) {
            throw new BusinessException(Result.SYS_FAILD, "参数错误(请求对象为空)");
        }
        BsEvidenceConfItem bsEvidenceConfItem = DataUtil.copyTo(bsEvidenceConfItemRequest, BsEvidenceConfItem.class);
        String userId = GlobalHeaderThreadLocal.getOrException().getUserId();
        if (th) {
            //添加
            if (StringUtil.isBlank(bsEvidenceConfItem.getClassifyCode()) || StringUtil.isBlank(bsEvidenceConfItem.getClassifyName()) || StringUtil.isBlank(bsEvidenceConfItem.getConfId())) {
                throw new BusinessException(Result.SYS_FAILD, "参数错误(配置编码/配置名称/配置表id)不能为空");
            }
            if (StringUtil.isBlank(bsEvidenceConfItem.getClassifyItemType())) {
                throw new BusinessException(Result.SYS_FAILD, "参数错误(证据项类型)不能为空");
            }
            bsEvidenceConfItem.setCreateUser(userId);
            bsEvidenceConfItem.setCreateTime(new Date());
            bsEvidenceConfItemMapper.insert(bsEvidenceConfItem);
        } else {
            //修改
            //验证当前数据是否存在
            final BsEvidenceConfItem byId = bsEvidenceConfItemMapper.getById(bsEvidenceConfItem.getId());
            if (byId == null) {
                throw new BusinessException(Result.SYS_FAILD, "修改数据不存在 id" + bsEvidenceConfItem.getId());
            }
            BsEvidenceConfItem newBsEvidenceConfItem = new BsEvidenceConfItem();
            DataUtil.copyProperties(byId, newBsEvidenceConfItem, getNullPropertyNames(byId));
            DataUtil.copyProperties(bsEvidenceConfItem, newBsEvidenceConfItem, getNullPropertyNames(bsEvidenceConfItem));
            newBsEvidenceConfItem.setOperateUser(userId);
            newBsEvidenceConfItem.setOperateTime(new Date());
            bsEvidenceConfItemMapper.update(newBsEvidenceConfItem);
        }
    }

    public static String[] getNullPropertyNames(Object source) {
        return BsEvidenceConfServiceImpl.getNullPropertyNames(source);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void del(BsEvidenceConfItemRequest bsEvidenceConfItemRequest) {
        EvidenceConfQueryIdsDto confQueryIdsDto = new EvidenceConfQueryIdsDto();
        confQueryIdsDto.setConfItemId(bsEvidenceConfItemRequest.getId());
        final List<EvidenceConfRespIdsDto> itemAndDetailIds = bsEvidenceConfMapper.findItemAndDetailIds(confQueryIdsDto);

        if (CollectionUtil.isNotEmpty(itemAndDetailIds)) {
            itemAndDetailIds.forEach(item -> {
                if (StringUtil.isNotEmpty(item.getItemDetailIds())) {
                    detailMapper.delete(item.getItemDetailIds());
                }
            });
        }
        bsEvidenceConfItemMapper.delete(bsEvidenceConfItemRequest.getId());

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void insertOrUpdateAll(BsEvidenceConfItemRequest bsEvidenceConfItemRequest) {
        boolean th = false;
        if (StringUtil.isBlank(bsEvidenceConfItemRequest.getId())) {
            th = true;
            bsEvidenceConfItemRequest.setId(snowFlake.generateId());
        }
        //详情集合取出
        List<BsEvidenceConfItemDetailRequest> bsEvidenceConfItemDetailRequest = bsEvidenceConfItemRequest.getBsEvidenceConfItemDetailRequest();
        //给详情赋值
        bsEvidenceConfItemDetailRequest.forEach(item -> item.setItemId(bsEvidenceConfItemRequest.getId()));
        //添加修改分类
        insertOrUpdate(bsEvidenceConfItemRequest, th);
        //全部重新添加分类得详情 如果id操作先删除再添加
        List<String> ids = bsEvidenceConfItemDetailRequest.stream().map(BsEvidenceConfItemDetailRequest::getId)
                .filter(StringUtil::isNotBlank).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(ids)) {
            detailMapper.dletByIds(ids, bsEvidenceConfItemRequest.getId());
        }
        //添加
        if (CollectionUtil.isNotEmpty(bsEvidenceConfItemDetailRequest)) {
            detailService.batchInsertOrUpdate(bsEvidenceConfItemDetailRequest);
        } else {
            detailMapper.delByItemId(bsEvidenceConfItemRequest.getId());
        }

    }

    @Override
    public Result<List<BsEvidenceConfItemResponse>> queryIdsByTable(List<String> ids) {
        List<BsEvidenceConfItem> bsEvidenceConfItems = bsEvidenceConfItemMapper.queryIdsByTable(ids);
        List<BsEvidenceConfItemResponse> bsEvidenceConfItemResponses = BsEvidenceConfItemConverter.INSTANCE.dosToRes(bsEvidenceConfItems);
        return Result.ok(bsEvidenceConfItemResponses);
    }
}
